<?php

namespace App\Repositories\Admin;

use App\BaseRepository;
use App\Helpers\Helpers;
use App\Model\Role;
use App\Model\UserAuthTag;
use App\Model\UserRole;
use Illuminate\Support\Facades\DB;

class ExpertUserRepository extends BaseRepository
{
    //模型名称
    protected $modelName = "App\User";

    protected function query()
    {
        return $this->model()->whereIn('userType',['expert','talent']);
    }

    protected function commonRules()
    {
        $authTags = UserAuthTag::codeList();
        $authTags = implode(',',$authTags);
        return [
            'userType' => 'required|in:expert,talent',
            'name' => 'required',
            'authTag' => 'required|in:'.$authTags,
            'avatar' => 'required|url',
            'intro' => 'required_if:userType,expert',
        ];
    }

    protected function commonMessages()
    {
        return [
            'userType.in' => '类型参数错误',
            'authTag.in' => '身份认证参数错误',
            'name.required' => '姓名必填',
            'avatar.required' => '未上传头像',
            'avatar.url' => '不是有效的头像',
            'intro.required' => '个人简介必填',
        ];
    }

    //获取保存到数据库的数据
    protected function getStoreFillData()
    {
        $d = $this->request->only('avatar','name','intro','userType','authTag');
        if ($d['userType'] == "expert") {
            $prefix = "ZJ";
        }else{
            $prefix = "DR";
        }
        $d['account'] = Helpers::createSerial('t_user','account',$prefix.substr(date('Y'),2));
        $d['chAuthTag'] = UserAuthTag::getNameByCode($d['authTag']);

        $d['password'] = bcrypt($this->request->input('account').'letsdrink');

        return $d;
    }

    //获取保存到数据库的数据
    protected function getUpdateFillData()
    {
        $d = $this->request->only('avatar','name','intro','authTag');
        $d['password'] = bcrypt($this->request->input('account').'letsdrink');
        $d['chAuthTag'] = UserAuthTag::getNameByCode($d['authTag']);
        return $d;
    }

    protected function afterStore($model)
    {
        $role = Role::where('code','=','expert')->first();
        if ($role) {
            $m = new UserRole();
            $m->role_id = $role->id;
            $m->user_id = $model->id;
            $m->save();
        }
    }
}